#include "PackageManager.h"
//#ifdef __COMPILE_LINUX__
#ifndef _MSC_VER
	#include <dlfcn.h>
#endif

#include "ConfigManager.h"
#include "Log.h"

#define IF_P			IPackage *p = GetPackageForId(IdPackage);	\
						if (p)	\
						{
#define AFTER_P			}	\
							\
						return NOT_VALID_ID_PACKAGE;

CPackageManager::CPackageManager()
{

}

CPackageManager::~CPackageManager()
{

}

s32 CPackageManager::GetNewPackageID()
{
	s32 ActualID = PackageList.size();
	return ActualID;
}

IPackage *CPackageManager::GetPackageForId(s32 Id)
{
	if ((u32)Id < PackageList.size())
		return PackageList[Id]->Package;
	else
		return NULL;
}

s32 CPackageManager::LoadPackagesFromFile(stringc File)
{
	ConfigManager->SetActualSection("PackagesToLoad");
	if (ConfigManager->ReadFile("Packages.cfg"))
	{
//		stringc PackId = "";
		stringc PackName = "";
		u32 PackId = 0;

		do
		{
//			PackId = "Package";

//			PackName =
		} while (PackName == "");
	}
}

s32 CPackageManager::LoadNewPackage(stringc FileName)
{
	IPackageData *pd = new IPackageData();

	pd->lib_handle = dlopen(FileName.c_str(), RTLD_LAZY);
	if (pd->lib_handle)
	{
		pd->gnpi = (GetNewPackageInstance*)dlsym(pd->lib_handle,"GetNewInstance");
		pd->gp = (GetPackage*)dlsym(pd->lib_handle,"GetPack");
		pd->dpi = (DestroyPackageInstance*)dlsym(pd->lib_handle,"DestroyPackage");
		pd->id = GetNewPackageID();
		pd->Package = pd->gnpi();
		PackageList.push_back(pd);
		return pd->id;
	}
	else
		return PACKAGE_FILE_NOT_FOUND;
}

s32 CPackageManager::UpdateAllPackages()
{
	bool Salir;
	s32 Index = 0;
	s32 ret;
	do
	{
		ret = UpdatePackage(Index);
		Salir = (ret == NOT_VALID_ID_PACKAGE);
		Index++;
	} while (!Salir);
}

s32 CPackageManager::StartPackage(s32 IdPackage)
{
	IF_P
		return p->PackageStart();
	AFTER_P
}

s32 CPackageManager::UpdatePackage(s32 IdPackage)
{
	IF_P
		return p->PackageUpdate();
	AFTER_P
}

s32 CPackageManager::PausePackage(s32 IdPackage)
{
	IF_P
		return p->PackagePause();
	AFTER_P
}

s32 CPackageManager::StopPackage(s32 IdPackage)
{
	return 0;
}

s32 CPackageManager::DestroyPackage(s32 IdPackage)
{
	return 0;
}

s32 CPackageManager::ShowPackageDetails(s32 IdPackage)
{
	IPackage *pack = GetPackageForId(IdPackage);
	if (pack)
	{
		pLogDebug << "Package " << pack->GetPackageName() << " loaded correctly" << endl;
		pLogDebug << "\tDescription: " << pack->GetPackageDescription() << endl;
		pLogDebug << "\tVersion: " << pack->GetVer() << "." << pack->GetSubVer() << "." << pack->GetRev() << endl;
		return PACKAGE_OPERATION_CORRECT;
	}

	return NOT_VALID_ID_PACKAGE;
}
